package com.wjf.resourceservice.service.impl;

import com.wjf.resourceservice.config.MinioProperties;
import com.wjf.resourceservice.service.FileService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import jakarta.annotation.PostConstruct;
import java.util.UUID;

@Slf4j
@Service
public class MinioFileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;
    
    @Autowired
    private MinioProperties minioProperties;

    @PostConstruct
    public void init() {
        // 确保 bucket 存在
        createBucketIfNotExists(minioProperties.getMusicBucketName());
        createBucketIfNotExists(minioProperties.getImageBucketName());
    }

    private void createBucketIfNotExists(String bucketName) {
        try {
            boolean found = minioClient.bucketExists(BucketExistsArgs.builder()
                    .bucket(bucketName)
                    .build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
            }
        } catch (Exception e) {
            log.error("初始化 MinIO bucket 失败", e);
            throw new RuntimeException("初始化 MinIO bucket 失败", e);
        }
    }

    @Override
    public String uploadMusic(MultipartFile file) {
        try {
            // 生成唯一文件名
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") 
                            + "_" + file.getOriginalFilename();
            
            // 上传文件到MinIO
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getMusicBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            
            // 构建并返回文件访问URL
            return String.format("%s/%s/%s", 
                    minioProperties.getEndpoint(),
                    minioProperties.getMusicBucketName(), 
                    fileName);
        } catch (Exception e) {
            log.error("上传音乐文件失败", e);
            throw new RuntimeException("上传音乐文件失败", e);
        }
    }

    @Override
    public String uploadImage(MultipartFile file) {
        try {
            String fileName = UUID.randomUUID().toString().replaceAll("-", "") 
                            + "_" + file.getOriginalFilename();
            
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getImageBucketName())
                    .object(fileName)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            
            return String.format("%s/%s/%s", 
                    minioProperties.getEndpoint(),
                    minioProperties.getImageBucketName(), 
                    fileName);
        } catch (Exception e) {
            log.error("上传图片文件失败", e);
            throw new RuntimeException("上传图片文件失败", e);
        }
    }

    @Override
    public void deleteFile(String url) {
        try {
            // 从URL中解析出bucket和对象名
            String[] parts = url.substring(minioProperties.getEndpoint().length() + 1).split("/");
            String bucket = parts[0];
            String object = parts[1];
            
            minioClient.removeObject(RemoveObjectArgs.builder()
                    .bucket(bucket)
                    .object(object)
                    .build());
        } catch (Exception e) {
            log.error("删除文件失败", e);
            throw new RuntimeException("删除文件失败", e);
        }
    }
}